package com.powernode.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.constant.QueueConstant;
import com.powernode.domain.User;
import com.powernode.mapper.UserMapper;
import com.powernode.service.UserService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.List;
import java.util.Map;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private UserMapper userMapper;


    @Autowired
    private UserService userService;

    @Override
    public void send(Map<String, Object> map) {
        // 组装数据，并将组装好的数据放在消息队列中
        String phoneNum = (String) map.get("phonenum");
        map.put("mobile", phoneNum);
        String verifyCode = RandomUtil.randomNumbers(4);
        stringRedisTemplate.opsForValue().set(phoneNum, verifyCode, Duration.ofMinutes(5));
        map.put("param", verifyCode);
        rabbitTemplate.convertAndSend(QueueConstant.PHONE_CODE_QUEUE, JSONUtil.toJsonStr(map));
    }

    @Override
    public void bindUserPhone(Map<String, Object> map) {
        // 1.
        String userId = (String)map.get("userId");
        String phoneNum = (String)map.get("phonenum");
        String code = (String)map.get("code");
        String verifyCode = stringRedisTemplate.opsForValue().get(phoneNum);
        if (StrUtil.isEmpty(verifyCode) || !verifyCode.equals(code)) {
            throw new RuntimeException("验证码错误");
        }

        User user = new User();
        user.setUserId(userId);
        user.setUserMobile(phoneNum);
        userMapper.update(user, new LambdaQueryWrapper<User>().eq(User::getUserId, user.getUserId()));
        // userService.update().set("user_mobile", phoneNum).eq("user_id", userId);

    }

    @Override
    public List<User> selectUserInfoByIds(List<String> ids) {

        return   userMapper.selectList(new LambdaQueryWrapper<User>()
                .in(User::getUserId, ids)
        );
    }
}
